
import const
# from typing import Union

def key_data2str(data, data_type):
    """
    :param data: Union[int,float,str]
    :param data_type: str 
    :retrun: str
    """
    if data_type == 'f':
        return f"[{int(data)}]"
    elif data_type == 's':
        return f"['{data}']"
    else:
        return data

def data2desc(data, data_type, hide_quotation_mark=False, color=None):
    """
    :param data: Union[int,float,str]
    :param data_type: str
    :param hide_quotation_mark: bool = False 是否隐藏引号
    :param color: str = None 添加对应颜色代码
    :return: str
    """

    res = ""
    if data_type == "f":
        res = f"{const.Colors[color]}{getPreciseData(data)}|r" if color else f"{getPreciseData(data)}"
    elif data_type == "p":
        res = f"{const.Colors[color]}{getPreciseData(data * 100)}%|r" if color else f"{getPreciseData(data * 100)}%"
    elif data_type == "t":
        if data % 60 == 0:
            data = data/60
            period = "分钟"
        else:
            period = "秒"
        data = str(int(data))
        res = f"{const.Colors['BLUE']}{data}|r{period}" # if color else f"{data}{period}"
    elif data_type == "s" and not hide_quotation_mark:
        res = f'"{data}"'
    elif data_type == "tab":
        res = '{ "' + data.replace(',', '", "') + '", }'
    elif data_type == "i":
        res = round(data)
    else:
        res = f"{data}"
    return res


def get_data_type(data):
    """
    :param data: Union[int,float,str]
    """
    # "-" 和 "." 不能在配置表中的字符串项中出现
    if (not "," in str(data)) and (not "|" in str(data)) and (str(data)[:1] == "-" or "." in str(data) or str(data).isdigit()):
        return "f"
    else:
        return "s"


def getPreciseData(num):
    """
    删除小数点后无意义的0
    :param num: Union[number,str]
    """
    isFloat = "." in str(num)
    if isFloat:
        s = "%.4f" % num
        index = len(s) - 1
        while True:
            if s[index] == "0":
                index = index - 1
            elif s[index] == ".":
                index = index - 1
                break
            else:
                break
        
        return s[0:index+1]

    return num